package net.gazhi.delonix.grac.web.controller;

import java.util.List;
import java.util.Set;
import java.util.TreeSet;

import javax.validation.Valid;

import net.gazhi.delonix.core.dao.PageInfo;
import net.gazhi.delonix.grac.entity.act.Action;
import net.gazhi.delonix.grac.entity.act.Module;
import net.gazhi.delonix.grac.entity.gru.Role;
import net.gazhi.delonix.grac.form.RoleForm;
import net.gazhi.delonix.grac.service.ActionService;
import net.gazhi.delonix.grac.service.RoleService;
import net.gazhi.delonix.grac.web.annonation.Handler;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

@Controller
@Handler(zh = "角色管理", en = "Roles")
@RequestMapping("/grac/role")
public class RoleController extends AbstractGracController {

	@Autowired
	private RoleService roleService;

	@Autowired
	private ActionService actionService;

	@Handler(zh = "列表", en = "List", redirectable = true)
	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public ModelAndView list(String keyword, Integer pageNo) {
		PageInfo pageInfo = new PageInfo(pageNo == null ? 1 : pageNo);
		List<Role> roles = this.roleService.search(keyword, pageInfo);
		return new ModelAndView().addObject("roles", roles).addObject("pageInfo", pageInfo);
	}

	@Handler(zh = "新增/修改表单页面", en = "Add/Modify Form Page", redirectable = true)
	@RequestMapping(value = "/edit", method = RequestMethod.GET)
	public ModelAndView edit(Long id) {
		Role role = null;
		if (id != null) {
			role = roleService.get(id);
		}
		List<Action> actions = actionService.list();
		Set<Module> modules = new TreeSet<Module>();
		for (Action act : actions) {
			act.getController().getActions().add(act);
			act.getController().getModule().getControllers().add(act.getController());
			modules.add(act.getController().getModule());
		}
		return new ModelAndView().addObject("role", role).addObject("modules", modules);
	}

	@Handler(zh = "保存角色", en = "Save Role")
	@RequestMapping(value = "/save", method = RequestMethod.POST)
	public ModelAndView save(@Valid @ModelAttribute("grac$role$form") RoleForm form, BindingResult result) {
		try {
			if (!result.hasErrors()) {
				this.roleService.save(form, result);
			}
		} catch (RuntimeException e) {
			ModelAndView mav = super.handleServiceException(e);
			if (mav != null) {
				return mav;
			}
		}
		return new ModelAndView();
	}

}
